﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.ObjectModel;
using SQLServerOptimizer.PL.WPF;
using SQLServerHealthCheck.Model;
using System.Threading;
using System.Windows.Threading;

namespace PlayGround.WPF
{
    class Class1 : DispatcherObject
    {
        public ObservableCollection<SQLServerInstance> SQLServerInstances = new ObservableCollection<SQLServerInstance>();
        public ObservableCollection<SQLServerInstance> ConnectedSQLServerInstances = new ObservableCollection<SQLServerInstance>();
        public ObservableCollection<IssueServer> issueServers = new ObservableCollection<IssueServer>();
        public ObservableCollection<DatabaseTrace> TraceSQLInstances = new ObservableCollection<DatabaseTrace>();
        ConnectionCheckWorker _statusworker;
        DataCollectionWorker worker;
        private DispatcherTimer TraceStatusCheckTimer = new DispatcherTimer(DispatcherPriority.Normal);
        HealthCheckDataContext dc;
      
        App shut;
        public void scan(App aap)
        {
            dc = new HealthCheckDataContext(System.Configuration.ConfigurationManager.AppSettings["ConnectionStringSSHCDatabase"].ToString());
            shut = aap;

            var instances = from a in dc.Services
                            where a.Authentication != null
                            select a;
            start(instances.ToList());


        }

        private void start(List<Service> instances)
        {

            foreach (var item in instances)
            {
                SQLServerInstances.Add(new SQLServerInstance { Authentication = item.Authentication, InstanceName = item.InstanceName, Login = item.Login, Password = item.Password, Port = item.Port.ToString() });

            }
            ConnectedSQLServerInstances = SQLServerInstances;
            worker = new DataCollectionWorker(this, ConnectedSQLServerInstances);
            worker.ProccessCompleted += new ProccesCompleted(worker_ProccessCompleted);
            _statusworker = new ConnectionCheckWorker(this, this.SQLServerInstances);
            _statusworker.StatusCheckProccessCompleted += new StatusCheckProccesCompleted(_statusworker_StatusCheckProccessCompleted);
            _statusworker.Start();
        }
        private void _statusworker_StatusCheckProccessCompleted()
        {

            if (this.ConnectedSQLServerInstances.Count > 0)
            {
         
                worker.Start();

            }
        }
        private void worker_ProccessCompleted()
        {


            try
            {
                new MailReport().mail("bram.crombach@gmail.com", "bram.crombach@gmail.com", "bram.crombach@gmail.com", "bierfiets4", "smtp.gmail.com", "587", "testmail");
            }
            catch(Exception e ) {  }
                shut.Shutdown();

   


        }
    }



}


